<template>
  <n-modal
    v-model:show="modalVisible"
    class="w-380px"
    preset="card"
    :title="title"
    :auto-focus="false"
    :bordered="true"
    :mask-closable="false"
    :close-on-esc="false"
    :on-after-leave="handleUpdateFormModelByModalType"
  >
    <n-form ref="formRef" :model="formModel" :rules="rules" @submit="handleSubmit">
      <n-form-item label="手机号" path="phone">
        <n-input v-model:value="formModel.phone" clearable placeholder="输入手机号" />
      </n-form-item>
      <n-form-item label="密码" path="password">
        <n-input
          v-model:value="formModel.password"
          type="password"
          :input-props="{ autocomplete: 'new-password' }"
          show-password-on="click"
          clearable
          :placeholder="passwordPlaceholder"
        />
      </n-form-item>
      <n-form-item label="姓名" path="userName">
        <n-input v-model:value="formModel.userName" placeholder="输入姓名" clearable />
      </n-form-item>
      <n-form-item label="供应商" path="supplierId">
        <supplier-select
          v-model:value="formModel.supplierId"
          :select-label="props.editData ? props.editData.supplierName : null"
        />
      </n-form-item>
      <n-form-item label="组织" path="organizationId">
        <organization-select
          v-model:value="formModel.organizationId"
          :select-label="props.editData ? props.editData.organizationName : null"
        />
      </n-form-item>
      <n-form-item label="状态" path="userStatus">
        <n-radio-group v-model:value="formModel.userStatus">
          <n-space>
            <n-radio label="启用" value="1" checked />
            <n-radio label="禁用" value="0" />
          </n-space>
        </n-radio-group>
      </n-form-item>
      <n-row :gutter="[24, 24]">
        <n-col :span="24" class="flex justify-end">
          <n-button type="primary" attr-type="submit">确认</n-button>
        </n-col>
      </n-row>
    </n-form>
  </n-modal>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue';
import type { FormInst } from 'naive-ui';
import { REGEXP_PWD } from '@/config';
import { fetchEditUser } from '@/service';
import { useAppStore } from '@/store';
import { formRules, createRequiredFormRule } from '@/utils';
import OrganizationSelect from '@/views/_builtin/login/components/PwdLogin/components/OrganizationSelect.vue';
import supplierSelect from './SupplierSelect.vue';

export interface Props {
  /** 弹窗可见性 */
  visible: boolean;
  /**
   * 弹窗类型
   * add: 新增
   * edit: 编辑
   */
  type?: 'add' | 'edit';
  /** 编辑的表格行数据 */
  editData?: any;
}
export type ModalType = NonNullable<Props['type']>;

const props = withDefaults(defineProps<Props>(), {
  type: 'add',
  editData: null
});

interface Emits {
  (e: 'update:visible', visible: boolean): void;
}
const emit = defineEmits<Emits>();
const modalVisible = computed({
  get() {
    return props.visible;
  },
  set(visible) {
    emit('update:visible', visible);
  }
});
const closeModal = () => {
  modalVisible.value = false;
};

const title = computed(() => {
  const titles: Record<ModalType, string> = {
    add: '新增账号',
    edit: '编辑账号'
  };
  return titles[props.type];
});

const passwordPlaceholder = computed(() => (props.type === 'add' ? '输入密码' : '如需修改密码请输入，否则请留空'));

const formRef = ref<HTMLElement & FormInst>();

const formModel = reactive(createDefaultFormModel());

const rules: any = reactive({
  userName: createRequiredFormRule('请输入用户名'),
  password: [
    {
      required: computed(() => props.type === 'add'),
      message: '请输入密码'
    },
    { pattern: REGEXP_PWD, message: '密码为6-18位数字/字符/符号，至少2种组合', trigger: 'input' }
  ],
  phone: formRules.phone,
  supplierId: createRequiredFormRule('请选择供应商'),
  organizationId: createRequiredFormRule('请选择组织'),
  userStatus: createRequiredFormRule('请选择用户状态')
});

function createDefaultFormModel(): any {
  return {
    userId: '',
    userName: '',
    password: '',
    phone: '',
    supplierId: null,
    organizationId: null,
    userStatus: '1'
  };
}

function handleUpdateFormModel(model: any) {
  Object.assign(formModel, model);
}
function handleUpdateFormModelByModalType() {
  const handlers: Record<ModalType, () => void> = {
    add: () => {
      const defaultFormModel = createDefaultFormModel();
      handleUpdateFormModel(defaultFormModel);
    },
    edit: () => {
      if (props.editData) {
        handleUpdateFormModel(props.editData);
      }
    }
  };
  handlers[props.type]();
}

const app = useAppStore();
function handleSubmit(e: any) {
  e.preventDefault();
  formRef.value
    ?.validate(async errors => {
      if (!errors) {
        const { data } = await fetchEditUser(formModel);
        if (data) {
          closeModal();
          window.$message?.success(`${title.value}成功`);
          handleUpdateFormModelByModalType();
          app.reloadPage();
        }
      }
    })
    .catch(() => {
      window.$message?.error(`${title.value}失败`);
    });
}

watch(
  () => props.visible,
  newValue => {
    if (newValue) {
      handleUpdateFormModelByModalType();
    }
  }
);
</script>
